package main

import (
	"flag"
	"io"
	"log"
	"os"
	"sync"

	"github.com/robfig/cron"
)

type stream struct {
	sync.Mutex
	io.WriteCloser
}

func (s *stream) Reset(stdout io.WriteCloser) io.WriteCloser {
	s.Lock()
	old := s.WriteCloser
	s.WriteCloser = stdout
	s.Unlock()
	return old
}

func (s *stream) Write(p []byte) (n int, err error) {
	s.Lock()
	n, err = s.WriteCloser.Write(p)
	s.Unlock()
	return
}

func main() {
	var output string
	flag.StringVar(&output, `output`, `logs/%Y%D%M.log`, `输出文件名`)
	flag.Parse()
	filename := build(output)
	jobs := cron.New()
	expr := spec(output)
	fd := new(stream)
	file, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
	if err != nil {
		log.Panic(err, filename)
	}
	fd.Reset(file)
	err = jobs.AddFunc(expr, func() {
		file1 := build(output)
		if file1 == filename {
			return
		}
		file, err := os.OpenFile(file1, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
		if err != nil {
			return
		}
		filename = file1
		old := fd.Reset(file)
		old.Close()
	})
	if err != nil {
		log.Fatal(err)
	}
	jobs.Start()
	io.Copy(fd, os.Stdin)
}
